package com.shioirikukuri.controller;

import com.shioirikukuri.common.result.Result;
import com.shioirikukuri.entity.DiningOrder;
import com.shioirikukuri.entity.ReservationDiningStatus;
import com.shioirikukuri.entity.SpecialPrice;
import com.shioirikukuri.service.IDiningOrderService;
import com.shioirikukuri.service.IReservationDiningStatusService;
import com.shioirikukuri.service.IReservationOrderService;
import com.shioirikukuri.service.ISpecialPriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/dining-orders")
public class DiningOrderController {

	@Autowired
	private IDiningOrderService diningOrderService;

	@Autowired
	private IReservationDiningStatusService reservationDiningStatusService;

	@Autowired
	private IReservationOrderService reservationOrderService;

	@Autowired
	private ISpecialPriceService specialPriceService;


	/**
	 * 申请创建空的点餐订单
	 * 创建空的点餐订单写入预定订单ID
	 * @param reservationOrderId 预定订单ID
	 * @return Result<Integer> 返回点餐订单ID 或 错误信息
	 */
	@PostMapping("/reservation/{reservationOrderId}")
	public Result<Integer> createEmptyDiningOrder(@PathVariable Integer reservationOrderId) {
		try {
			// 创建空的点餐订单,由数据库生成DiningOrderId
			DiningOrder diningOrder = new DiningOrder();
			diningOrder.setDishes("");
			diningOrder.setCombos("");
			diningOrder.setBaseTotal(0.0);
			diningOrder.setPriceAdjustment(0.0);
			diningOrder.setCouponId(null);
			diningOrder.setFinalTotal(0.0);
			diningOrder.setCreateTime(null);

			// 创建点餐订单
			diningOrderService.createDiningOrder(diningOrder);

			Integer diningOrderId = diningOrder.getDiningOrderId();

			// 设置关联表的预定订单ID，订单状态为待点餐
			ReservationDiningStatus status = new ReservationDiningStatus();
			status.setReservationOrderId(reservationOrderId);
			status.setDiningOrderId(diningOrderId);
			status.setDiningOrderStatus(ReservationDiningStatus.STATUS_WAITING_ORDER);

			// 检查预约订单中的服务价格是否为0，若为0则更新预约订单状态为已支付
			Double servicePrice = reservationOrderService.getServicePriceByOrderId(reservationOrderId);
			if (servicePrice != null && servicePrice == 0) {
				status.setReservationOrderStatus(ReservationDiningStatus.STATUS_PAID);
			}

			reservationDiningStatusService.createReservationDiningStatus(status);

			return Result.success(diningOrderId);

		} catch (Exception e) {
			// 可根据具体异常类型做更细粒度处理
			return Result.error(500, "创建点餐订单失败：" + e.getMessage());
		}
	}

	/**
	 * 提交点餐订单详情(更新前面创建的空订单订单）
	 * @param diningOrderId diningOrder  前面的空订单ID和点餐订单详情
	 * @return Result<> 返回成功信息 或 错误信息
	 */
	@PutMapping("/{id}")
	public Result<Void> submitDiningOrder(
			@PathVariable("id") Integer diningOrderId,
			@RequestBody DiningOrder diningOrder) {

		try {
			// 设置订单ID，确保更新的是正确的订单
			diningOrder.setDiningOrderId(diningOrderId);
			// 设置创建时间
			diningOrder.setCreateTime(LocalDateTime.now());


			// 设置订单状态为待支付
			ReservationDiningStatus status = new ReservationDiningStatus();
			status.setDiningOrderId(diningOrderId);
			status.setDiningOrderStatus(ReservationDiningStatus.STATUS_WAITING_PAYMENT);
			reservationDiningStatusService.createReservationDiningStatus(status);

			// 获取特殊价格
			List<SpecialPrice> specialPrices = specialPriceService.getAllSpecialPrices();

			// 判断当前时间是否存在可应用的特殊价格时间段
			LocalDateTime now = LocalDateTime.now(); // 当前时间

			Optional<SpecialPrice> applicablePrice = specialPrices.stream()
					.filter(price -> {
						LocalDateTime start = price.getStartTime();
						LocalDateTime end = price.getEndTime();
						return !now.isBefore(start) && !now.isAfter(end); // 包括等于边界
					})
					.findFirst();

			// 设置点餐总价
			diningOrder.setFinalTotal(diningOrder.getBaseTotal());

			// 应用特殊价格波动
			if (applicablePrice.isPresent()) {
				SpecialPrice sp = applicablePrice.get();
				diningOrder.setPriceAdjustment(sp.getPriceRatio().doubleValue());
			}

			// 计算最终总价
			diningOrder.calculateFinalTotal();

			// 调用服务层进行更新
			diningOrderService.updateDiningOrder(diningOrder);

			return Result.success(null);

		} catch (Exception e) {
			return Result.error(500, "提交点餐订单失败：" + e.getMessage());
		}
	}




	@GetMapping
	public List<DiningOrder> getAllDiningOrders() {
		return diningOrderService.getAllDiningOrders();
	}

	@GetMapping("/{diningOrderId}")
	public DiningOrder getDiningOrderById(@PathVariable Integer diningOrderId) {
		return diningOrderService.getDiningOrderById(diningOrderId);
	}

	@PostMapping
	public void createDiningOrder(@RequestBody DiningOrder diningOrder) {
		diningOrderService.createDiningOrder(diningOrder);
	}

	@DeleteMapping("/{diningOrderId}")
	public void deleteDiningOrderById(@PathVariable Integer diningOrderId) {
		diningOrderService.deleteDiningOrderById(diningOrderId);
	}


}